package three;

public class A050 {


    public static void main(String[] args) {
        char[][] a = {{'1','1','1','1','0'},{'1','1','0','1','0'},{'1','1','0','0','0'},{'0','0','0','0','0'}};
        //numIslands(a);
    }


    boolean[][] check;
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};
    int m,n,ret;
    public int numIslands(char[][] grid) {
        m=grid.length;n=grid[0].length;
        check = new boolean[m][n];
        for(int i=0;i<m;i++) {
            for(int j=0;j<n;j++) {
                if(!check[i][j] && grid[i][j]=='1') {
                    ret++;
                    floodfill(grid,i,j);
                }
            }
        }
        return ret;
    }

    public void floodfill(char[][] grid,int i,int j) {
        check[i][j]=true;
        for(int k=0;k<4;k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x<m&&y<n && x>=0 && y>=0 && !check[x][y] && grid[x][y]=='1') {
                floodfill(grid,x,y);
            }
        }
    }
}
